package cn.tedu.charging.order.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/ws/server/{userId}")
public class WebSocketServer {

    private static ConcurrentHashMap<Integer, Session> sessionMap = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(@PathParam("userId") Integer userId,Session session){
        log.debug("WebSocketServer onOpen");
        sessionMap.put(userId,session);
        log.info("用户{}连接成功,session:{}",userId,session);
    }

    @OnClose
    public void onClose(@PathParam("userId") Integer userId,Session session){
        log.debug("WebSocketServer onClose");
        sessionMap.remove(userId);
        log.info("用户{}断开连接,session:{}",userId,session);
    }

    @OnMessage
    public void onMessage(String message,Session session){
        log.info("收到用户{},消息：{}",session,message);
    }

    @OnError
    public void onError(@PathParam("userId") Integer userId,Throwable e){
        log.info("用户{}发生异常",userId);
        e.printStackTrace();
    }

    public void sendMessage(Integer userId,String message){
        Session session = sessionMap.get(userId);
        if(session != null){
            session.getAsyncRemote().sendText(message);
        }else {
            log.info("用户{}不在线",userId);
        }
    }
}
